package com.Junit.lock;

import com.Junit.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

public class RedisLock extends AbstractLock{
    private String lockKey;
    private long expireTime;

    public RedisLock(String lock, long expireTime) {
        this.lockKey = lock;
        this.expireTime = expireTime;
    }

    public boolean lock(boolean useTimeOut, long timeOut, TimeUnit timeUnit, boolean interrupt) {

        if(RedisUtil.setNx(lockKey,String.valueOf(expireTime))){
            this.setLock(true);
            this.setCurrentThread(Thread.currentThread());
            return true;
        }
        String expireTime = RedisUtil.get(lockKey);
        if(isTimeExpired(expireTime)){
            if(RedisUtil.casSetValue(lockKey,expireTime)){
                this.setLock(true);
                this.setCurrentThread(Thread.currentThread());
                return true;
            }
        }
        return false;
    }

    public void unlock0() {
        RedisUtil.delKey(lockKey);
    }

    private boolean isTimeExpired(String value) {
        if (StringUtils.isBlank(value))
            return true;
        Long val = Long.valueOf(value);
        // 这里拿服务器的时间来比较
        return val == null || val < RedisUtil.getRedisServiceTime();
    }


}
